"""
权限管理帮助函数
提供权限系统的CRUD操作和权限检查功能
"""
from typing import List, Optional
from sqlmodel import Session, select
from app.users.models import User, Role, Permission, UserRole, RolePermission
from app.users.schema import (
    RoleCreate, RoleUpdate, PermissionCreate, PermissionUpdate,
    UserRoleCreate, RolePermissionCreate
)


# ==================== 角色管理 ====================

def create_role(session: Session, role_data: RoleCreate) -> Role:
    """创建角色"""
    role = Role(**role_data.model_dump())
    session.add(role)
    session.commit()
    session.refresh(role)
    return role


def get_role_by_id(session: Session, role_id: int) -> Optional[Role]:
    """根据ID获取角色"""
    return session.get(Role, role_id)


def get_role_by_code(session: Session, code: str) -> Optional[Role]:
    """根据代码获取角色"""
    statement = select(Role).where(Role.code == code)
    return session.exec(statement).first()


def get_all_roles(session: Session, skip: int = 0, limit: int = 100) -> List[Role]:
    """获取所有角色"""
    statement = select(Role).offset(skip).limit(limit)
    return session.exec(statement).all()


def update_role(session: Session, role_id: int, role_data: RoleUpdate) -> Optional[Role]:
    """更新角色"""
    role = session.get(Role, role_id)
    if not role:
        return None
    
    role_dict = role_data.model_dump(exclude_unset=True)
    for field, value in role_dict.items():
        setattr(role, field, value)
    
    session.add(role)
    session.commit()
    session.refresh(role)
    return role


def delete_role(session: Session, role_id: int) -> bool:
    """删除角色"""
    role = session.get(Role, role_id)
    if not role:
        return False
    
    session.delete(role)
    session.commit()
    return True


# ==================== 权限管理 ====================

def create_permission(session: Session, permission_data: PermissionCreate) -> Permission:
    """创建权限"""
    permission = Permission(**permission_data.model_dump())
    session.add(permission)
    session.commit()
    session.refresh(permission)
    return permission


def get_permission_by_id(session: Session, permission_id: int) -> Optional[Permission]:
    """根据ID获取权限"""
    return session.get(Permission, permission_id)


def get_permission_by_code(session: Session, code: str) -> Optional[Permission]:
    """根据代码获取权限"""
    statement = select(Permission).where(Permission.code == code)
    return session.exec(statement).first()


def get_all_permissions(session: Session, skip: int = 0, limit: int = 100) -> List[Permission]:
    """获取所有权限"""
    statement = select(Permission).offset(skip).limit(limit)
    return session.exec(statement).all()


def update_permission(session: Session, permission_id: int, permission_data: PermissionUpdate) -> Optional[Permission]:
    """更新权限"""
    permission = session.get(Permission, permission_id)
    if not permission:
        return None
    
    permission_dict = permission_data.model_dump(exclude_unset=True)
    for field, value in permission_dict.items():
        setattr(permission, field, value)
    
    session.add(permission)
    session.commit()
    session.refresh(permission)
    return permission


def delete_permission(session: Session, permission_id: int) -> bool:
    """删除权限"""
    permission = session.get(Permission, permission_id)
    if not permission:
        return False
    
    session.delete(permission)
    session.commit()
    return True


# ==================== 用户角色管理 ====================

def assign_role_to_user(session: Session, user_id: int, role_id: int) -> UserRole:
    """为用户分配角色"""
    # 检查是否已经存在该关联
    statement = select(UserRole).where(
        UserRole.user_id == user_id,
        UserRole.role_id == role_id
    )
    existing = session.exec(statement).first()
    if existing:
        return existing
    
    user_role = UserRole(user_id=user_id, role_id=role_id)
    session.add(user_role)
    session.commit()
    session.refresh(user_role)
    return user_role


def remove_role_from_user(session: Session, user_id: int, role_id: int) -> bool:
    """移除用户的角色"""
    statement = select(UserRole).where(
        UserRole.user_id == user_id,
        UserRole.role_id == role_id
    )
    user_role = session.exec(statement).first()
    if not user_role:
        return False
    
    session.delete(user_role)
    session.commit()
    return True


def get_user_roles(session: Session, user_id: int) -> List[Role]:
    """获取用户的所有角色"""
    statement = select(Role).join(UserRole).where(UserRole.user_id == user_id)
    return session.exec(statement).all()


def get_users_by_role(session: Session, role_id: int) -> List[User]:
    """获取拥有指定角色的所有用户"""
    statement = select(User).join(UserRole).where(UserRole.role_id == role_id)
    return session.exec(statement).all()


# ==================== 角色权限管理 ====================

def assign_permission_to_role(session: Session, role_id: int, permission_id: int) -> RolePermission:
    """为角色分配权限"""
    # 检查是否已经存在该关联
    statement = select(RolePermission).where(
        RolePermission.role_id == role_id,
        RolePermission.permission_id == permission_id
    )
    existing = session.exec(statement).first()
    if existing:
        return existing
    
    role_permission = RolePermission(role_id=role_id, permission_id=permission_id)
    session.add(role_permission)
    session.commit()
    session.refresh(role_permission)
    return role_permission


def remove_permission_from_role(session: Session, role_id: int, permission_id: int) -> bool:
    """移除角色的权限"""
    statement = select(RolePermission).where(
        RolePermission.role_id == role_id,
        RolePermission.permission_id == permission_id
    )
    role_permission = session.exec(statement).first()
    if not role_permission:
        return False
    
    session.delete(role_permission)
    session.commit()
    return True


def get_role_permissions(session: Session, role_id: int) -> List[Permission]:
    """获取角色的所有权限"""
    statement = select(Permission).join(RolePermission).where(RolePermission.role_id == role_id)
    return session.exec(statement).all()


def get_roles_by_permission(session: Session, permission_id: int) -> List[Role]:
    """获取拥有指定权限的所有角色"""
    statement = select(Role).join(RolePermission).where(RolePermission.permission_id == permission_id)
    return session.exec(statement).all()


# ==================== 权限检查 ====================

def get_user_permissions(session: Session, user_id: int) -> List[Permission]:
    """获取用户的所有权限（通过角色）"""
    statement = (
        select(Permission)
        .join(RolePermission)
        .join(Role)
        .join(UserRole)
        .where(UserRole.user_id == user_id)
        .distinct()
    )
    return session.exec(statement).all()


def check_user_permission(session: Session, user_id: int, permission_code: str) -> bool:
    """检查用户是否拥有指定权限"""
    # 超级管理员拥有所有权限
    user = session.get(User, user_id)
    if user and user.is_superuser:
        return True
    
    statement = (
        select(Permission)
        .join(RolePermission)
        .join(Role)
        .join(UserRole)
        .where(
            UserRole.user_id == user_id,
            Permission.code == permission_code
        )
    )
    permission = session.exec(statement).first()
    return permission is not None


def check_user_resource_permission(session: Session, user_id: int, resource: str, action: str) -> bool:
    """检查用户是否对指定资源有指定操作的权限"""
    # 超级管理员拥有所有权限
    user = session.get(User, user_id)
    if user and user.is_superuser:
        return True
    
    statement = (
        select(Permission)
        .join(RolePermission)
        .join(Role)
        .join(UserRole)
        .where(
            UserRole.user_id == user_id,
            Permission.resource == resource,
            Permission.action == action
        )
    )
    permission = session.exec(statement).first()
    return permission is not None


# ==================== 初始化权限数据 ====================

def init_default_permissions(session: Session) -> None:
    """初始化默认权限"""
    default_permissions = [
        # 用户管理权限
        PermissionCreate(
            name="用户查看",
            code="user:read",
            resource="user",
            action="read",
            description="查看用户信息"
        ),
        PermissionCreate(
            name="用户创建",
            code="user:create",
            resource="user",
            action="create",
            description="创建新用户"
        ),
        PermissionCreate(
            name="用户更新",
            code="user:update",
            resource="user",
            action="update",
            description="更新用户信息"
        ),
        PermissionCreate(
            name="用户删除",
            code="user:delete",
            resource="user",
            action="delete",
            description="删除用户"
        ),
        # 角色管理权限
        PermissionCreate(
            name="角色查看",
            code="role:read",
            resource="role",
            action="read",
            description="查看角色信息"
        ),
        PermissionCreate(
            name="角色创建",
            code="role:create",
            resource="role",
            action="create",
            description="创建新角色"
        ),
        PermissionCreate(
            name="角色更新",
            code="role:update",
            resource="role",
            action="update",
            description="更新角色信息"
        ),
        PermissionCreate(
            name="角色删除",
            code="role:delete",
            resource="role",
            action="delete",
            description="删除角色"
        ),
        # 权限管理权限
        PermissionCreate(
            name="权限查看",
            code="permission:read",
            resource="permission",
            action="read",
            description="查看权限信息"
        ),
        PermissionCreate(
            name="权限创建",
            code="permission:create",
            resource="permission",
            action="create",
            description="创建新权限"
        ),
        PermissionCreate(
            name="权限更新",
            code="permission:update",
            resource="permission",
            action="update",
            description="更新权限信息"
        ),
        PermissionCreate(
            name="权限删除",
            code="permission:delete",
            resource="permission",
            action="delete",
            description="删除权限"
        ),
    ]
    
    for perm_data in default_permissions:
        existing = get_permission_by_code(session, perm_data.code)
        if not existing:
            create_permission(session, perm_data)


def init_default_roles(session: Session) -> None:
    """初始化默认角色"""
    default_roles = [
        RoleCreate(
            name="超级管理员",
            code="super_admin",
            description="拥有所有权限的超级管理员"
        ),
        RoleCreate(
            name="管理员",
            code="admin",
            description="拥有大部分管理权限的管理员"
        ),
        RoleCreate(
            name="普通用户",
            code="user",
            description="普通用户，只有基本权限"
        ),
    ]
    
    for role_data in default_roles:
        existing = get_role_by_code(session, role_data.code)
        if not existing:
            create_role(session, role_data)


def assign_default_permissions_to_roles(session: Session) -> None:
    """为默认角色分配权限"""
    # 获取角色
    super_admin_role = get_role_by_code(session, "super_admin")
    admin_role = get_role_by_code(session, "admin")
    user_role = get_role_by_code(session, "user")
    
    if not all([super_admin_role, admin_role, user_role]):
        return
    
    # 获取所有权限
    all_permissions = get_all_permissions(session)
    
    # 超级管理员拥有所有权限
    for permission in all_permissions:
        assign_permission_to_role(session, super_admin_role.id, permission.id)
    
    # 管理员拥有除超级管理员权限外的所有权限
    admin_permissions = [p for p in all_permissions if not p.code.startswith("super_admin")]
    for permission in admin_permissions:
        assign_permission_to_role(session, admin_role.id, permission.id)
    
    # 普通用户只有查看权限
    user_permissions = [p for p in all_permissions if p.action == "read"]
    for permission in user_permissions:
        assign_permission_to_role(session, user_role.id, permission.id)
